<?php

namespace App\Http\Controllers\Admin\Finance\Receivable;

use App\Http\Controllers\Admin\Base\ExchangeRate;
use App\Http\Controllers\Controller;
use App\Http\Requests\airline\base\BanRequest;
use App\Models\airline\base\FlightModel as BaseFlightModel;
use App\Models\DictionaryModel;
use App\Models\finance\PayableTakeOrderDetailModel;
use App\Models\finance\PayableTakeOrderModel;
use App\Models\finance\PayableTmpModel;
use App\Models\finance\ReceivableTakeOrderDetailModel;
use App\Models\finance\ReceivableTakeOrderModel;
use App\Models\OrderModel;
use App\Models\RecBillModel;
use App\Models\TakeOrderModel;
use App\Models\TakeOrderRecModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TakeOrder extends Controller
{
    use BanRequest;

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $take_order_sn = $request->input('take_order_sn', '');


        $query = ReceivableTakeOrderModel::query()->with(['take_order', 'flight', 'customer']);

        if($take_order_sn){
            $find = TakeOrderModel::query()->where('take_order_sn', $take_order_sn)->first();
            $take_order_id = $find->id ?? 0;
            $query->where('take_order_id', $take_order_id);
        }


        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $flight_date = $item->flight ? date('Y-m-d', strtotime($item->flight->take_off_time)) : '';
            //航班号
            $airline_flight_ids = $item->flight?->items?->pluck('airline_flight_id') ?? [];
            $flight_number = BaseFlightModel::whereIn('id', $airline_flight_ids)->pluck('flight_number')->toArray();

            $res = [
                'id' => $item->id,
                'customer_id' => $item->customer_id,
                'customer_name' => $item->customer->name ?? '',
                'take_order_id' => $item->take_order_id,
                'flight_date' => $flight_date,
                'sn' => $item->take_order->sn ?? '',
                'air_company' => $item->flight->air_company ?? '',
                'goods_attr' => OrderModel::GOODS_ATTR_MAPS[$item->goods_attr] ?? '',
                'take_warehouse' => $item->take_order->take_warehouse ?? '',
                'master' => $item->take_order->master ?? '',
                'start_port_code' => $item->flight->start_port_code ?? '',
                'arrive_port_code' => $item->flight->arrive_port_code ?? '',
                'big_pkgs' => $item->big_pkgs,
                'volume_weight' => $item->take_order->volume_weight,
                'reality_weight' => $item->take_order->reality_weight,
                'servicer' => $item->take_order->servicer ?? '',
                'operator' => $item->take_order->operator ?? '',
                'flight_number' => implode(',', $flight_number),
                'hk_land' => TakeOrderModel::HK_LAND_MAPS[$item->take_order->hk_land] ?? '',
                'hk_provide' => TakeOrderModel::HK_PROVIDE_MAPS[$item->take_order->hk_provide] ?? '',
//                'tmp_id' => $item->tmp_id,
//                'tmp_name' => $item->tmp->name ?? '',
//                'amount' => $item->amount,
//                'amount_cny' => $item->amount_cny,
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }



    public function detail(Request $request) {
        $id = $request->input('id');

        $take_order = PayableTakeOrderModel::find($id);
        if(!$take_order) {
            return $this->error('提单不存在');
        }

        $detail = ReceivableTakeOrderDetailModel::with(['currency'])->where('receivable_take_order_id', $id)->get();

        $list = $detail->map(function($item) {
            $res = [
                'id' => $item->id,
                'name' => $item->name,
                'number' => $item->number,
                'unit' => $item->unit,
                'price' => $item->price,
                'currency_id' => $item->currency_id,
                'currency_code' => $item->currency->short_code ?? '',
                'rate' => $item->rate,
                'amount' => $item->amount,
                'amount_cny' => $item->amount_cny,
            ];
            return $res;
        });

        $list = $list->toArray() ?? [];

        $amount_total = $detail->sum('amount') ?? 0;
        $amount_total_cny = $detail->sum('amount_cny') ?? 0;
        $total = [
            'amount' => $amount_total,
            'amount_cny' => $amount_total_cny,
        ];

        return $this->success(['list' => $list, 'total' => $total]);
    }


    public function detail_add(Request $request) {
        $id = $request->input('receivable_take_order_id');
        $params = $request->all();

        $take_order = PayableTakeOrderModel::find($id);
        if(!$take_order) {
            return $this->error('提单不存在');
        }

        $detail = new ReceivableTakeOrderDetailModel();
        $detail->receivable_take_order_id = $id;
        $detail->take_order_id = $take_order->take_order_id;
        $detail->customer_id = $take_order->customer_id;
        $detail->flight_date = $take_order->flight_date;
        $detail->name = $params['name'];
        $detail->number = $params['number'];
        $detail->unit = $params['unit'];
        $detail->price = $params['price'];
        $detail->currency_id = $params['currency_id'];
        $detail->rate = $params['rate'];
        $detail->amount = $params['amount'];
        $detail->amount_cny = $params['amount_cny'];
        $detail->save();

        return $this->success();
    }


    public function detail_update(Request $request, $id) {
        $params = $request->all();

        $detail = ReceivableTakeOrderDetailModel::find($id);
        if(!$detail) {
            return $this->error('明细不存在');
        }

        $detail->name = $params['name'];
        $detail->number = $params['number'];
        $detail->unit = $params['unit'];
        $detail->price = $params['price'];
        $detail->currency_id = $params['currency_id'];
        $detail->rate = $params['rate'];
        $detail->amount = $params['amount'];
        $detail->amount_cny = $params['amount_cny'];
        $detail->save();

        return $this->success();
    }

    public function detail_delete($id) {
        $detail = ReceivableTakeOrderDetailModel::find($id);
        if(!$detail) {
            return $this->error('明细不存在');
        }

        $detail->delete();

        return $this->success();
    }


    public function bill_create(Request $request) {
        $ids = $request->input('ids',  []);

        $take_orders = PayableTakeOrderModel::whereIn('id', $ids)->whereNotNull('bill_id')->get();

        if($take_orders->count() != count($ids)) {
            return $this->error('部分提单已生成账单');
        }

        $customer_id  = $take_orders->pluck('customer_id')->unique()->toArray();
        if(count($customer_id) > 1) {
            return $this->error('部分提单不属于同一客户');
        }

        $bill= new RecBillModel();
        $bill->customer_id = $take_orders->first()->customer_id;


    }

}
